from sanic import Sanic
from sanic.response import text
from sanic.response import json
import requests
import cv2
import base64
import time
import json as Json
import re
import difflib


app = Sanic("ocr-server")


def hub_predict(img):
    data = {'images':[img]}
    headers = {"Content-type": "application/json"}
    url = "http://127.0.0.1:8866/predict/ocr_system"
    start_time = time.time()
    r = requests.post(url=url, headers=headers, data=Json.dumps(data))
    print(f'识别耗时：{time.time() - start_time}')
    # 打印预测结果
    return r.json().get('results')

def pd_predict(img):
    data = {"key": ["image"], "value": [img]}
    headers = {"Content-type": "application/json"}
    url = "http://127.0.0.1:9998/ocr/prediction"
    r = requests.post(url=url, headers=headers, data=Json.dumps(data))
    values = r.json().get('value')
    return eval(values[0])


@app.post("/hub/idcard/predict")
async def hello_world(request):
    res = {
        'msg': 'ok',
        'code': 0,
        'data': {}
    }
    if len(request.files.keys()) > 1:
        res['msg'] = '单次只能传入一个文件'
        res['code'] = 1
        return json(res)
    f = request.files.get(list(request.files.keys())[0])
    img = base64.b64encode(f.body).decode('utf8')
    predict_res = hub_predict(img) 
    return_dict = res['data']
    is_back = False
    for item in ['中华人民共和国', '居民身份证', '签发机关', '有效期限']:
        if item in [obj['text'] for obj in predict_res[0]]:
            is_back = True
            break
    return_dict['is_back'] = is_back
    if is_back:
        for obj in predict_res[0]:
            item = obj['text']
            print(item)
            if '-' in item:
                return_dict['date'] = item.replace('有效期限', '')
            elif item.replace(' ', '') in ['中华人民共和国', '居民身份证', '签发机关', '有效期限']:
                continue
            else:
                return_dict['sign'] = item.replace('签发机关', '')
        return json(res)
    for obj in predict_res[0]:
        item = obj['text']
        print(item)
        if '姓名' in item:
            return_dict['name'] = item.replace('姓名', '')
        elif len(item) == 18 and (item.isnumeric() or item[:-1].isnumeric()):
            return_dict['idNo'] = item
        elif '公民身份号码' in item:
            return_dict['idNo'] = item.replace('公民身份号码', '').replace(' ', '')
        elif '性别' in item:
            return_dict['gender'] = item.replace('性别', '')
        elif '民族' in item:
            return_dict['nation'] = item.replace('民族', '')
        elif '出生' in item:
            return_dict['birthday'] = '-'.join(re.findall( r'\d+', item, re.M|re.I))
        elif '住址' in item:
            return_dict['address'] = item.replace('住址', '')
        elif item == '公民身份号码':
            continue
        elif item.replace(' ', '') in ['中华人民共和国', '居民身份证', '签发机关', '有效期限']:
            continue
        else:
            address = return_dict.get('address', '')
            address += item
            return_dict['address'] = address
    return json(res)

@app.post("/pd/idcard/predict")
async def hello_world(request):
    res = {
        'msg': 'ok',
        'code': 0,
        'data': {}
    }
    if len(request.files.keys()) > 1:
        res['msg'] = '单次只能传入一个文件'
        res['code'] = 1
        return json(res)
    f = request.files.get(list(request.files.keys())[0])
    img = base64.b64encode(f.body).decode('utf8')
    predict_res = pd_predict(img)
    return_dict = res['data']
    is_back = False
    for item in ['中华人民共和国', '居民身份证', '签发机关', '有效期限']:
        if item in [obj for obj in predict_res]:
            is_back = True
            break
    return_dict['is_back'] = is_back
    if is_back:
        for item in predict_res:
            print(item)
            if '-' in item:
                return_dict['date'] = item.replace('有效期限', '')
            elif item.replace(' ', '') in ['中华人民共和国', '居民身份证', '签发机关', '有效期限']:
                continue
            else:
                return_dict['sign'] = item.replace('签发机关', '')
        return json(res)
    for item in predict_res:
        print(item)
        if '姓名' in item:
            return_dict['name'] = item.replace('姓名', '')
        elif len(item) == 18 and (item.isnumeric() or item[:-1].isnumeric()):
            return_dict['idNo'] = item
        elif '公民身份号码' in item:
            return_dict['idNo'] = item.replace('公民身份号码', '').replace(' ', '')
        elif '性别' in item:
            return_dict['gender'] = item.replace('性别', '')
        elif '民族' in item:
            return_dict['nation'] = item.replace('民族', '')
        elif '出生' in item:
            return_dict['birthday'] = '-'.join(re.findall( r'\d+', item, re.M|re.I))
        elif '住址' in item:
            return_dict['address'] = item.replace('住址', '')
        elif item == '公民身份号码':
            continue
        elif item.replace(' ', '') in ['中华人民共和国', '居民身份证', '签发机关', '有效期限']:
            continue
        else:
            address = return_dict.get('address', '')
            address += item
            return_dict['address'] = address
    return json(res)


@app.post("/pd/yyzz/predict")
async def hello_world(request):
    res = {
        'msg': 'ok',
        'code': 0,
        'data': {}
    }
    if len(request.files.keys()) > 1:
        res['msg'] = '单次只能传入一个文件'
        res['code'] = 1
        return json(res)
    f = request.files.get(list(request.files.keys())[0])
    img = base64.b64encode(f.body).decode('utf8')
    predict_res = pd_predict(img)
    return_dict = res['data']
    for item in predict_res:
        item  = item.replace(' ', '')
        print(item)
        if '名称' in item:
            return_dict['name'] = item.replace('名称', '')
        elif len(item) == 18:
            return_dict['unifyCode'] = item
        elif '统一社会信用代码' in item:
            return_dict['unifyCode'] = item.replace('统一社会信用代码', '')
        elif '负责人' in item:
            return_dict['legalPerson'] = item.replace('负责人', '')
        elif '经营者' in item:
            return_dict['legalPerson'] = item.replace('经营者', '')
        elif '类型' in item:
            return_dict['busType'] = item.replace('类型', '')
        elif '法定代表人' in item:
            return_dict['legalPerson'] = item.replace('法定代表人', '')
        elif '注册资本' in item:
            return_dict['registerPrice'] = item.replace('注册资本', '')
        elif '成立日期' in item:
            return_dict['biudDate'] = item.replace('成立日期', '')
        elif '营业期限' in item:
            return_dict['expireDate'] = item.replace('营业期限', '')
        elif '住所' in item:
            return_dict['address'] = item.replace('住址', '')
        elif item in ['营业执照', '（副本）', '社会统一信用代码', '经营范围', '登记机关', '经营场所', '负责人']:
            continue
        elif [i in item for i in ['省', '市', '区', '县', '街', '号']].count(True) > 2 or [i in item for i in ['楼', '室', '号', '村', '县', '乡', '层']].count(True) > 2:
            address = return_dict.get('address', '')
            address += item
            return_dict['address'] = address
        else:
            business = return_dict.get('business', '')
            business += item
            return_dict['business'] = business
    if difflib.SequenceMatcher(None, return_dict.get('busType', ''), '个体工商户').quick_ratio() > 0.85:
        return_dict['composeForm'] = '个人经营'
    return json(res)


if __name__ == "__main__":
    app.run(host='0.0.0.0', port='8080', debug=True)